//
//  MyDownLoadViewController.m
//  DolphinMusic
//
//  Created by liuhaiyang on 15/4/2.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "MyDownLoadViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MyDownloadTableViewCell.h"
#import "DataBaseHandler.h"
#import "LoadingTableViewCell.h"

@interface MyDownLoadViewController () < UITableViewDataSource, UITableViewDelegate>


@property (nonatomic, retain)NSMutableData *receiveData;
@property (nonatomic, retain)UILabel *nullLabel;
@property (nonatomic, retain)UISegmentedControl *segment;


@end


@implementation MyDownLoadViewController
- (void)dealloc
{
    [_segment release];
    [_nullLabel release];
    [_str release];
    [_receiveData release];
    [_song_id release];
    [_tableView1 release];
    [_tableView2 release];
    [_arr1 release];
    [_arr2 release];
    [_deleteAllButton release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorFromHexCode:@"##f2eada"];
    
    UIWindow *window = [[[UIApplication sharedApplication] windows] firstObject];
    PlayView *playView = (PlayView*)[window viewWithTag:10001];
    playView.target = self.navigationController;
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 20)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 release];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 20, VIEW_WIDTH, 44)];
    view2.backgroundColor = [UIColor colorFromHexCode:@"#33a3dc"];
    [self.view addSubview:view2];
    [view2 release];
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 20, 50, 44);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 20, 20)];
    imageView.image = [UIImage imageNamed:@"backButton.png"];
    [leftButton addSubview:imageView];
    [imageView release];

    [leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 27, 100, 30)];
    titleLabel.text = @"我的下载";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:titleLabel];
    [titleLabel release];
    
    self.scrollback = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height - 100 - 70.0 / 667 * VIEW_HEIGHT)];
    self.scrollback.backgroundColor = [UIColor clearColor];
    self.scrollback.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    self.scrollback.showsHorizontalScrollIndicator = NO;
    self.scrollback.delegate = self;
    self.scrollback.pagingEnabled = YES;
    [self.view addSubview:self.scrollback];
    [_scrollback release];
    
    self.nullLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH / 2 - 80, VIEW_HEIGHT / 5, 160, 30)];
    self.nullLabel.text = @"当前没有已下载的歌曲";
    self.nullLabel.textAlignment =  NSTextAlignmentCenter;
    self.nullLabel.layer.cornerRadius = 5;
    self.nullLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.nullLabel.layer.borderWidth = 1;
    
    self.nullLabel.font = [UIFont systemFontOfSize:14];
    [self.scrollback addSubview:self.nullLabel];
    self.nullLabel.hidden = YES;
    
    
    // 数组
   NSMutableArray *array = [[DataBaseHandler shareInstance] selectAllInFilePath];
    self.arr1 = [NSMutableArray arrayWithArray:array];
    
    NSInteger downLoadedSongCount = self.arr1.count;
    if (downLoadedSongCount == 0) {
        self.nullLabel.hidden = NO;
    }
    for (NSInteger j = 0; j < downLoadedSongCount / 2; j++) {
        [self.arr1 exchangeObjectAtIndex:j withObjectAtIndex:downLoadedSongCount - 1 - j];
    }
    
    
    NSMutableArray *array1 = [[DataBaseHandler shareInstance] selectAllInLoading];
    self.arr2 = [NSMutableArray arrayWithArray:array1];
    NSInteger downLoadingSongCount = self.arr2.count;
    for (NSInteger j = 0; j < downLoadingSongCount / 2; j++) {
        [self.arr2 exchangeObjectAtIndex:j withObjectAtIndex:downLoadingSongCount - 1 - j];
    }
    
    
    
    // 已下载
    
    NSString *downloadStr = [NSString stringWithFormat:@"已下载(%ld)", downLoadedSongCount];
    NSString *downLoadingStr = [NSString stringWithFormat:@"下载中(%ld)", downLoadingSongCount];
    
    self.segment = [[UISegmentedControl alloc] initWithItems:@[downloadStr, downLoadingStr]];
    self.segment.frame = CGRectMake(50, 70, self.view.frame.size.width - 100, 30);
    self.segment.tintColor = [UIColor grayColor];
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 0;
    [self.view addSubview:self.segment];
    [self.segment release];
    
    
    
    
    self.tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH - 10, self.arr1.count * 60)];
    self.tableView1.delegate = self;
    self.tableView1.dataSource = self;
    [_tableView1  registerClass:[MyDownloadTableViewCell class] forCellReuseIdentifier:@"reuse"];
    self.tableView1.rowHeight = 60;
    self.tableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView1.showsVerticalScrollIndicator = NO;
    self.tableView1.backgroundColor = [UIColor clearColor];
    [self.scrollback addSubview:self.tableView1];
    
    [_tableView1 release];
   
    self.tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(VIEW_WIDTH, 0, VIEW_WIDTH - 10, self.arr2.count * 60)];
    self.tableView2.delegate = self;
    self.tableView2.dataSource = self;
    [_tableView2  registerClass:[LoadingTableViewCell class] forCellReuseIdentifier:@"reuse1"];
    self.tableView2.rowHeight = 60;
    self.tableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView2.showsVerticalScrollIndicator = NO;
    self.tableView2.backgroundColor = [UIColor clearColor];
    [self.scrollback addSubview:self.tableView2];
    [_tableView2 release];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receieveNotification:) name:@"MyDownloadControllerReload" object:nil];
    [center addObserver:self selector:@selector(receieveNotification:) name:@"loadingReload" object:nil];
    [center addObserver:self selector:@selector(receieveNotification:) name:@"downLoadComplite" object:nil];
    

    // 清除所有按钮
    self.deleteAllButton = [UIButton buttonWithType:UIButtonTypeSystem];

    self.deleteAllButton.frame = CGRectMake((VIEW_WIDTH - 150) / 2, self.tableView1.frame.size.height + 10, 150, 20);
    [self.deleteAllButton setTitle:@"删除所有已下载歌曲" forState:UIControlStateNormal];
    self.deleteAllButton.tintColor = [UIColor grayColor];
    self.deleteAllButton.layer.borderWidth = 1;
    self.deleteAllButton.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    self.deleteAllButton.layer.cornerRadius = 5;
    
    if (self.arr1.count == 0) {
        self.deleteAllButton.frame = CGRectMake(0, 0, 0, 0);
    }
    [self.deleteAllButton addTarget:self action:@selector(deleteAllButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollback addSubview:self.deleteAllButton];
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.scrollback) {
        self.segment.selectedSegmentIndex = (scrollView.contentOffset.x + VIEW_WIDTH / 2) / VIEW_WIDTH;
    }
}

- (void)segmentAction:(UISegmentedControl *)segment
{
    
    self.arr1 = [[DataBaseHandler shareInstance] selectAllInFilePath];
    NSInteger downLoadedSongCount = self.arr1.count;
    for (NSInteger j = 0; j < downLoadedSongCount / 2; j++) {
        [self.arr1 exchangeObjectAtIndex:j withObjectAtIndex:downLoadedSongCount - 1 - j];
    }
    
    
    self.arr2 = [[DataBaseHandler shareInstance] selectAllInLoading];
    NSInteger downLoadingSongCount = self.arr2.count;
    for (NSInteger j = 0; j < downLoadingSongCount / 2; j++) {
        [self.arr2 exchangeObjectAtIndex:j withObjectAtIndex:downLoadingSongCount - 1 - j];
    }
    
    [self.tableView1 reloadData];
    [self.tableView2 reloadData];
    
    
    if (segment.selectedSegmentIndex == 0) {
        self.scrollback.contentOffset = CGPointMake(0, 0);
    } else {
        self.scrollback.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView1) {
        return self.arr1.count;
    } else {
        return self.arr2.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView1) {
        MyDownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        Song *song = [self.arr1 objectAtIndex:indexPath.row];
        cell.song = song;
        cell.backgroundColor = [UIColor clearColor];
        return cell;
     
    } else {
      LoadingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1"];
        Song *song = [self.arr2 objectAtIndex:indexPath.row];
        cell.song = song;
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    
   
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView1) {
        
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MusicPlayViewController *musicVC = [MusicPlayViewController shareInstance];
    Song *song = [self.arr1 objectAtIndex:indexPath.row];
    musicVC.type = @"music";
    musicVC.playingNumber = indexPath.row;
    musicVC.playSongArr = [NSMutableArray array];
    for (Song *song1 in self.arr1) {
        [musicVC.playSongArr addObject:song1.song_id];
    }
    musicVC.singerName = song.author;
    musicVC.songTitle = song.title;
    musicVC.songID = song.song_id;
                      
                      }
}

- (void)viewWillAppear:(BOOL)animated
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIButton *button = (UIButton *) [window viewWithTag:1000];
    button.hidden = YES;
    
    
    self.arr1 = [[DataBaseHandler shareInstance] selectAllInFilePath];
    
    
    NSInteger downLoadedSongCount = self.arr1.count;
    for (NSInteger j = 0; j < downLoadedSongCount / 2; j++) {
        [self.arr1 exchangeObjectAtIndex:j withObjectAtIndex:downLoadedSongCount - 1 - j];
    }
    
    self.arr2 = [[DataBaseHandler shareInstance] selectAllInLoading];
    
    NSInteger downLoadingSongCount = self.arr2.count;
    
    for (NSInteger j = 0; j < downLoadingSongCount / 2; j++) {
        [self.arr2 exchangeObjectAtIndex:j withObjectAtIndex:downLoadingSongCount - 1 - j];
    }
    
    [self.tableView1 reloadData];
    [self.tableView2 reloadData];
    
    
    
    
}

- (void)leftButtonAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)receieveNotification:(NSNotification *)noti
{
    
    self.arr1 = [[DataBaseHandler shareInstance] selectAllInFilePath];

    self.tableView1.frame = CGRectMake(0, 0, VIEW_WIDTH - 10, self.arr1.count * 60);
    self.deleteAllButton.frame = CGRectMake((VIEW_WIDTH - 150) / 2, self.tableView1.frame.size.height + 10, 150, 20);
    
    if (self.arr1.count == 0) {
        self.deleteAllButton.frame = CGRectMake(0, 0, 0, 0);
        self.nullLabel.hidden = NO;
    }
    
    
    NSInteger downLoadedSongCount = self.arr1.count;
    for (NSInteger j = 0; j < downLoadedSongCount / 2; j++) {
        [self.arr1 exchangeObjectAtIndex:j withObjectAtIndex:downLoadedSongCount - 1 - j];
    }
    
    self.arr2 = [[DataBaseHandler shareInstance] selectAllInLoading];
    self.tableView2.frame = CGRectMake(VIEW_WIDTH, 0, VIEW_WIDTH - 10, self.arr2.count * 60);
    NSInteger downLoadingSongCount = self.arr2.count;
    for (NSInteger j = 0; j < downLoadingSongCount / 2; j++) {
        [self.arr2 exchangeObjectAtIndex:j withObjectAtIndex:downLoadingSongCount - 1 - j];
    }
    
    [self.segment setTitle:[NSString stringWithFormat:@"已下载(%ld)", self.arr1.count] forSegmentAtIndex:0];
    [self.segment setTitle:[NSString stringWithFormat:@"下载中(%ld)", self.arr2.count] forSegmentAtIndex:1];
    
    
    [self.tableView1 reloadData];
    [self.tableView2 reloadData];
}


- (void)deleteAllButtonAction:(UIButton *)button
{
    NSLog(@"deleteall");
    // 删除表
    [[DataBaseHandler shareInstance] deleteTableFilePath];
    [[DataBaseHandler shareInstance] creatTableFilePath];
    
    
    self.arr1 = [[DataBaseHandler shareInstance] selectAllInFilePath];
    
    NSInteger downLoadedSongCount = self.arr1.count;
    for (NSInteger j = 0; j < downLoadedSongCount / 2; j++) {
        [self.arr1 exchangeObjectAtIndex:j withObjectAtIndex:downLoadedSongCount - 1 - j];
    }
    
    self.arr2 = [[DataBaseHandler shareInstance] selectAllInLoading];
    
    [self.segment setTitle:@"已下载(0)" forSegmentAtIndex:0];
    [self.segment setTitle:[NSString stringWithFormat:@"下载中(%ld)", self.arr2.count] forSegmentAtIndex:1];

    self.nullLabel.hidden = NO;
    [self.tableView1 reloadData];
    [self.deleteAllButton removeFromSuperview];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
